package com.fenghuajueli.idiomppp.ui.idiompin;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.idiomppp.adapter.IdiomFillTextGridAdapter;
import com.fenghuajueli.idiomppp.adapter.IdiomGridAdapter;
import com.fenghuajueli.idiomppp.database.IdiomDaoUtils;
import com.fenghuajueli.idiomppp.databinding.ActivityIdiomPinPlayBinding;
import com.fenghuajueli.idiomppp.entity.IdiomPinEntity;
import com.fenghuajueli.idiomppp.entity.IdiomPinParentEntity;
import com.fenghuajueli.idiomppp.entity.IdiomShiYiEntity;
import com.fenghuajueli.idiomppp.utils.MmkvKey;
import com.fenghuajueli.idiomppp.utils.RuntimeDataUtils;
import com.fenghuajueli.libbasecoreui.listener.OnBaseClick;
import com.fenghuajueli.libbasecoreui.listener.OnListClickListener;
import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class IdiomPinPlayActivity extends BaseActivity {
    IdiomGridAdapter idiomGridAdapter;

    private List<IdiomPinEntity> idiomPinEntityList;
    private List<IdiomPinEntity> idiomPinDefaultEntityList;
    GridView gridView;
    private IdiomPinParentEntity idiomPinParentEntity;
    private List<IdiomPinEntity> fillIdiomList;//需要填充的文字集合
    GridView bottomFillTextGridView;
    RelativeLayout containerView;
    LinearLayout idiomShiYiContainer;
    TextView idiomName;
    TextView idiomShiyi;
    Button ivBack;
    TextView tvTitle;

    IdiomFillTextGridAdapter idiomFillTextGridAdapter;
    private AlertDialog.Builder builder;
    private List<List<IdiomPinEntity>> successRowList;
    private List<List<IdiomPinEntity>> successColumnList;
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    private Boolean isJieLongMode = false;//是否是接龙模式

    private ActivityIdiomPinPlayBinding binding;
    private void initview() {
        gridView = binding.gridView;
        bottomFillTextGridView = binding.bottomFillTextGridView;
        containerView = binding.containerView;
        idiomShiYiContainer = binding.idiomShiYiContainer;
        idiomName = binding.idiomName;
        idiomShiyi = binding.idiomShiyi;
        ivBack = binding.ivBack;
        tvTitle = binding.tvTitle;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityIdiomPinPlayBinding.inflate(getLayoutInflater());
        MyStatusBarUtils.setStatusBarWhite(this,"#12003E");
        setContentView(binding.getRoot());
        initview();
        isJieLongMode = getIntent().getBooleanExtra("mode", false);

        if(isJieLongMode){
            tvTitle.setText("成语接龙");
        }else {
            tvTitle.setText("成语拼拼");
        }
        ivBack.setOnClickListener(v -> onBackPressed());
//        ImageLoadManager.loadForViewGroup(containerView, R.mipmap.aa_szxl_bj);
        idiomPinParentEntity = RuntimeDataUtils.idiomPinParentEntity;
        init();
    }

    private void init() {
        idiomShiYiContainer.setVisibility(View.GONE);
        if (idiomPinParentEntity != null) {
            idiomPinDefaultEntityList = new ArrayList<>();
            idiomPinEntityList = RuntimeDataUtils.idiomPinParentEntity.getIdiomPinEntityList();
            for (int i = 0; i < 100; i++) {
                idiomPinDefaultEntityList.add(new IdiomPinEntity((i) % 10, (99 - i) / 10, -1, ""));
            }
            fillIdiomList = new ArrayList<>();
            for (int i = 0; i < idiomPinParentEntity.getIdiomPinEntityList().size(); i++) {
                if (idiomPinParentEntity.getIdiomPinEntityList().get(i).getStatus() == 0) {
                    idiomPinParentEntity.getIdiomPinEntityList().get(i).setFill(false);
                    idiomPinParentEntity.getIdiomPinEntityList().get(i).setFillText("");
                    idiomPinParentEntity.getIdiomPinEntityList().get(i).setBottomFill(false);
                    fillIdiomList.add(idiomPinParentEntity.getIdiomPinEntityList().get(i));
                }
            }
            Collections.shuffle(fillIdiomList);
            idiomGridAdapter = new IdiomGridAdapter(this, idiomPinDefaultEntityList, idiomPinEntityList, fillIdiomList);
            idiomGridAdapter.setOnSelectedListener(new OnListClickListener<IdiomPinEntity>() {
                @Override
                public void itemClick(int position, IdiomPinEntity data) {

                }
            });
            idiomGridAdapter.setOnSelectedCancelListener(new OnListClickListener<IdiomPinEntity>() {
                @Override
                public void itemClick(int position, IdiomPinEntity data) {
                    idiomFillTextGridAdapter.recoveryItem(data.getFillText());
                }
            });
            idiomGridAdapter.setOnSuccessListener(new OnBaseClick<Integer>() {
                @Override
                public void onClick(Integer integer) {
                    //全部填充正确
                    showPassDialog();
                }
            });
            idiomGridAdapter.setOnSingleCheckRightListener(new OnBaseClick<String>() {
                @Override
                public void onClick(String s) {
                    //某一个成语填充正确了
                    try {
                        IdiomShiYiEntity idiomShiYiEntity = IdiomDaoUtils.getIdiomShiYiManager().getOneData(s);
                        if (idiomShiYiEntity != null) {
                            idiomName.setText(idiomShiYiEntity.getIdiom() + "(" + idiomShiYiEntity.getPronounce() + ")");
                            idiomShiyi.setText(idiomShiYiEntity.getExplain());
                            idiomShiYiContainer.setVisibility(View.VISIBLE);
                            delayHide();
                        }
                    } catch (Exception e) {

                    }
                }
            });
            findRowRightWord();
            findColumnRightWord();
            gridView.setAdapter(idiomGridAdapter);
            initBottomTextList();
        }
    }

    /**
     * 定时隐藏
     */
    private void delayHide() {
        Observable.timer(3, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

            @Override
            public void onNext(Long aLong) {
                idiomShiYiContainer.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void findRowRightWord() {
        successRowList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            List<IdiomPinEntity> rowData = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                IdiomPinEntity check = new IdiomPinEntity();
                check.setRow(i);
                check.setColumn(j);
                if (idiomPinEntityList.contains(check)) {
                    rowData.add(idiomPinEntityList.get(idiomPinEntityList.indexOf(check)));
                }
            }
            Collections.sort(rowData, new Comparator<IdiomPinEntity>() {
                @Override
                public int compare(IdiomPinEntity idiomPinEntity, IdiomPinEntity t1) {
                    int diff = idiomPinEntity.getColumn() - t1.getColumn();
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            List<IdiomPinEntity> successList = new ArrayList<>();
            for (int k = 0; k < rowData.size(); k++) {
                if (rowData.get(k).getRow() == i) {
                    if (k + 1 < rowData.size()) {
                        if (rowData.get(k).getColumn() + 1 == rowData.get(k + 1).getColumn()) {
                            //相邻的词语
                            if (!successList.contains(rowData.get(k))) {
                                successList.add(rowData.get(k));
                            }
                            successList.add(rowData.get(k + 1));
                            if (successList.size() == 4) {
                                successRowList.add(successList);
                                successList = new ArrayList<>();
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < successRowList.size(); i++) {
            List<IdiomPinEntity> idiomPinEntities = successRowList.get(i);
            String data = "";
            for (int j = 0; j < idiomPinEntities.size(); j++) {
                data = data + idiomPinEntities.get(j).getWord();
            }
            LogUtils.d("得到的行词语：" + data);
        }
        idiomGridAdapter.setSuccessRowList(successRowList);
    }


    private void findColumnRightWord() {
        successColumnList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            List<IdiomPinEntity> rowData = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                IdiomPinEntity check = new IdiomPinEntity();
                check.setRow(j);
                check.setColumn(i);
                if (idiomPinEntityList.contains(check)) {
                    rowData.add(idiomPinEntityList.get(idiomPinEntityList.indexOf(check)));
                }
            }
            Collections.sort(rowData, new Comparator<IdiomPinEntity>() {
                @Override
                public int compare(IdiomPinEntity idiomPinEntity, IdiomPinEntity t1) {
                    int diff = idiomPinEntity.getColumn() - t1.getColumn();
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            List<IdiomPinEntity> successList = new ArrayList<>();
            for (int k = 0; k < rowData.size(); k++) {
                if (rowData.get(k).getColumn() == i) {
                    if (k + 1 < rowData.size()) {
                        if (rowData.get(k).getRow() + 1 == rowData.get(k + 1).getRow()) {
                            //相邻的词语
                            if (!successList.contains(rowData.get(k))) {
                                successList.add(rowData.get(k));
                            }
                            successList.add(rowData.get(k + 1));
                            if (successList.size() == 4) {
                                successColumnList.add(successList);
                                successList = new ArrayList<>();
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < successColumnList.size(); i++) {
            List<IdiomPinEntity> idiomPinEntities = successColumnList.get(i);
            Collections.reverse(idiomPinEntities);
            String data = "";
            for (int j = 0; j < idiomPinEntities.size(); j++) {
                data = data + idiomPinEntities.get(j).getWord();
            }
            LogUtils.d("得到的列词语：" + data);
        }
        idiomGridAdapter.setSuccessColumnList(successColumnList);
    }


    /**
     * 初始化底部需要填充的文字
     */
    private void initBottomTextList() {
        if (fillIdiomList.size() > 6) {
            idiomFillTextGridAdapter = new IdiomFillTextGridAdapter(this, 8, fillIdiomList);
            bottomFillTextGridView.setNumColumns(8);
        } else {
            idiomFillTextGridAdapter = new IdiomFillTextGridAdapter(this, 6, fillIdiomList);
            bottomFillTextGridView.setNumColumns(6);
        }
        idiomFillTextGridAdapter.setOnListClickListener(new OnListClickListener<IdiomPinEntity>() {
            @Override
            public void itemClick(int position, IdiomPinEntity data) {
                idiomGridAdapter.fillText(data.getWord());
            }
        });
        bottomFillTextGridView.setAdapter(idiomFillTextGridAdapter);
    }


    /**
     * 显示通关之后的提示，进入下一关
     */
    private void showPassDialog() {

        String msg = "";
        if (isJieLongMode) {
            if (MmkvUtils.mmkv.decodeInt(MmkvKey.IdiomJieLongPass.name(), 0) <= idiomPinParentEntity.getIndex()) {
                MmkvUtils.mmkv.encode(MmkvKey.IdiomJieLongPass.name(), idiomPinParentEntity.getIndex() + 1);
            }
            msg = "恭喜通过第" + (idiomPinParentEntity.getIndex() - 1799) + "关";
        } else {
            if (MmkvUtils.mmkv.decodeInt(MmkvKey.IdiomPinPass.name(), 0) <= idiomPinParentEntity.getIndex()) {
                MmkvUtils.mmkv.encode(MmkvKey.IdiomPinPass.name(), idiomPinParentEntity.getIndex() + 1);
            }
            msg = "恭喜通过第" + (idiomPinParentEntity.getIndex() + 1) + "关";
        }
        builder = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg)
                .setNegativeButton("下一关", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (isJieLongMode) {
                            if (idiomPinParentEntity.getIndex() - 1800 + 1 < RuntimeDataUtils.idiomJieLongParentEntityList.size()) {
                                idiomPinParentEntity = RuntimeDataUtils.idiomJieLongParentEntityList.get(idiomPinParentEntity.getIndex() - 1800 + 1);
                                RuntimeDataUtils.idiomPinParentEntity = idiomPinParentEntity;
                                init();
                            }
                        } else {
                            if (idiomPinParentEntity.getIndex() + 1 < RuntimeDataUtils.idiomPinParentEntityList.size()) {
                                idiomPinParentEntity = RuntimeDataUtils.idiomPinParentEntityList.get(idiomPinParentEntity.getIndex() + 1);
                                RuntimeDataUtils.idiomPinParentEntity = idiomPinParentEntity;
                                init();
                            }
                        }
                    }
                }).setNeutralButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }
}
